#include "move_video_object_tracking.h"

Move_Video_Object_Tracking::Move_Video_Object_Tracking(QWidget *parent)
    : CommonGraphicsView{parent}
{
    this->setWindowTitle("视频中移动对象统计");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频");
    connect(btn,&QPushButton::clicked,[=](){
        choiceVideo();
    });

}


void Move_Video_Object_Tracking::choiceVideo(){
    path = QFileDialog::getOpenFileName(this,"请选择视频","/Users/yangwei/Downloads/",tr("Image Files(*.mp4 *.avi)"));
    qDebug()<<"视频路径："<<path;
    showMoveVideoObjectTracking(path.toStdString().c_str());
}

void Move_Video_Object_Tracking::showMoveVideoObjectTracking(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);

    if(!capture.isOpened()){
        qDebug()<<"无法加载视频文件";
        return;
    }
    Ptr<BackgroundSubtractor> mogSubstractor = createBackgroundSubtractorMOG2();
    Mat frame,gauss,mask;
    Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
    int count=0;
    char text[8];
    while(capture.read(frame)){
        GaussianBlur(frame,gauss,Size(5,5),0,0);
        mogSubstractor->apply(gauss,mask);//获取mask
        threshold(mask,mask,0,255,THRESH_BINARY|cv::THRESH_OTSU);
        //执行形态学操作
        morphologyEx(mask,mask,MORPH_OPEN,kernel);
        dilate(mask,mask,kernel,Point(-1,-1));
        imshow("mask",mask);

        //找到最大轮廓定位外接矩形
        vector<vector<Point>> contours;
        vector<Vec4i> heri;
        //寻找最大外接矩形
        findContours(mask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
        count = 0;
        for(size_t i = 0;i<contours.size();i++){
            double area = contourArea(contours[i]);
            if(area<5000){
                continue;
            }
            Rect rect = boundingRect(contours[i]);
            qDebug()<<rect.width<<":"<<rect.height;
            if (rect.width < 200 || rect.height < 100) continue;
            count++;
            rectangle(frame,rect,Scalar(0,0,255),3,8);
            sprintf(text,"%d",count);
            putText(frame,text,Point(rect.x+rect.width/2,rect.y+rect.height/2),FONT_ITALIC, FONT_HERSHEY_PLAIN,Scalar(0,255,0),2,8);
        }


        imshow("frame",frame);

        int c = waitKey(1);
        if(c==27){
            break;
        }
    }
    capture.release();

}
